package ywpt.web.action.people;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

 

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.ecside.table.limit.Limit;
import org.ecside.util.RequestUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import ywpt.components.acegi.domain.Operation;
import ywpt.components.acegi.domain.User;
import ywpt.core.Constants;
import ywpt.core.SystemMessage;
import ywpt.core.exception.UniqueConstraintException;
import ywpt.core.util.DateTools;
import ywpt.core.util.StringTools;
import ywpt.core.web.BaseAction;
import ywpt.model.JobInfo;
import ywpt.model.PeopleEducation;
import ywpt.model.PeopleExperience;
import ywpt.model.PeopleFamily;
import ywpt.model.PeopleInfo;
import ywpt.model.PeopleScans;
import ywpt.model.PeopleTrain;
import ywpt.model.SysMsgInfo;
import ywpt.service.people.EducationService;
import ywpt.service.people.ExperienceService;
import ywpt.service.people.FamilyService;
import ywpt.service.people.PeopleService;
import ywpt.service.people.TrainService;
import ywpt.service.system.UserService;
import ywpt.service.work.SysMsgInfoService;
import ywpt.web.common.OperationConstants;
import ywpt.web.common.PublicFunction;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class PeopleAction extends BaseAction implements ModelDriven<PeopleInfo>, Preparable{

	/**
	 * 人事Action
	 */
	private static final long serialVersionUID = -4267105641932991044L;
	private static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd");
	private static int DEFAULT_PAGE_SIZE = 50;
	private Long id;
	private Long departId;
	private String departName;
	private String headPhoto;
	
	private Long jiguanId;
	private String jiguanName;
	
	private Long xueliId;
	private String xueliName;
	
	private Long positionId;
	private String positionName;
	
	private Long checkerId;
	
	private int gongling;//工龄
	
	private PeopleInfo peopleInfo;
	private PeopleService peopleService;
	private List<PeopleInfo> peopleInfoList = new ArrayList<PeopleInfo>();
 	
	private EducationService educationService;
	private ExperienceService experienceService;
	private TrainService trainService;
	private FamilyService familyService;

	
	private SysMsgInfoService sysMsgInfoService;
	// 文件的上传
	private File upload;// 实际上传文件
	private String uploadFileName; // 上传文件名
	
	private boolean[] popedom=new boolean[Constants.POPEDOM_LEN];//Ȩ������
		
	//查询相关
	private String qCode;
	private Long qDepartId;
	private Long qPositionId;
	private Long qXueliId;
	private String qPeopleName;
	private String qPoliticalStatus;
	private String qIdNumber;
	private int 	qState;
	private String qRZStart;
	private String qRZEnd;
	private String qZZStart;
	private String qZZEnd;	

	private int self;
	
	
	public int getSelf() {
		return self;
	}

	public void setSelf(int self) {
		this.self = self;
	}

	public String getQCode() {
		return qCode;
	}

	public void setQCode(String code) {
		qCode = code;
	}

	public Long getQDepartId() {
		return qDepartId;
	}

	public void setQDepartId(Long departId) {
		qDepartId = departId;
	}

	public Long getQPositionId() {
		return qPositionId;
	}

	public void setQPositionId(Long positionId) {
		qPositionId = positionId;
	}

	public Long getQXueliId() {
		return qXueliId;
	}

	public void setQXueliId(Long xueliId) {
		qXueliId = xueliId;
	}

	public String getQPeopleName() {
		return qPeopleName;
	}

	public void setQPeopleName(String peopleName) {
		qPeopleName = peopleName;
	}

	public String getQPoliticalStatus() {
		return qPoliticalStatus;
	}

	public void setQPoliticalStatus(String politicalStatus) {
		qPoliticalStatus = politicalStatus;
	}

	public String getQIdNumber() {
		return qIdNumber;
	}

	public void setQIdNumber(String idNumber) {
		qIdNumber = idNumber;
	}

	public int getQState() {
		return qState;
	}

	public void setQState(int state) {
		qState = state;
	}

	public String getQRZStart() {
		return qRZStart;
	}

	public void setQRZStart(String start) {
		qRZStart = start;
	}

	public String getQRZEnd() {
		return qRZEnd;
	}

	public void setQRZEnd(String end) {
		qRZEnd = end;
	}

	public String getQZZStart() {
		return qZZStart;
	}

	public void setQZZStart(String start) {
		qZZStart = start;
	}

	public String getQZZEnd() {
		return qZZEnd;
	}

	public void setQZZEnd(String end) {
		qZZEnd = end;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long getDepartId() {
		return departId;
	}

	public void setDepartId(Long departId) {
		this.departId = departId;
	}

	public String getDepartName() {
		return departName;
	}

	public void setDepartName(String departName) {
		this.departName = departName;
	}

	public PeopleInfo getPeopleInfo() {
		return peopleInfo;
	}

	public void setPeopleInfo(PeopleInfo peopleInfo) {
		this.peopleInfo = peopleInfo;
	}

	public PeopleService getPeopleService() {
		return peopleService;
	}

	public void setPeopleService(PeopleService peopleService) {
		this.peopleService = peopleService;
	}

	public List<PeopleInfo> getPeopleInfoList() {
		return peopleInfoList;
	}

	public void setPeopleInfoList(List<PeopleInfo> peopleInfoList) {
		this.peopleInfoList = peopleInfoList;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String getHeadPhoto() {
		return headPhoto;
	}

	public void setHeadPhoto(String headPhoto) {
		this.headPhoto = headPhoto;
	}
	public EducationService getEducationService() {
		return educationService;
	}

	public void setEducationService(EducationService educationService) {
		this.educationService = educationService;
	}

	public ExperienceService getExperienceService() {
		return experienceService;
	}

	public void setExperienceService(ExperienceService experienceService) {
		this.experienceService = experienceService;
	}

	public TrainService getTrainService() {
		return trainService;
	}

	public void setTrainService(TrainService trainService) {
		this.trainService = trainService;
	}

	public FamilyService getFamilyService() {
		return familyService;
	}

	public void setFamilyService(FamilyService familyService) {
		this.familyService = familyService;
	}
	public Long getPositionId() {
		return positionId;
	}

	public void setPositionId(Long positionId) {
		this.positionId = positionId;
	}

	public String getPositionName() {
		return positionName;
	}

	public void setPositionName(String positionName) {
		this.positionName = positionName;
	}
	public Long getXueliId() {
		return xueliId;
	}

	public void setXueliId(Long xueliId) {
		this.xueliId = xueliId;
	}

	public String getXueliName() {
		return xueliName;
	}

	public void setXueliName(String xueliName) {
		this.xueliName = xueliName;
	}
	public int getGongling() {
		return gongling;
	}

	public void setGongling(int gongling) {
		this.gongling = gongling;
	}
	public Long getJiguanId() {
		return jiguanId;
	}

	public void setJiguanId(Long jiguanId) {
		this.jiguanId = jiguanId;
	}

	public String getJiguanName() {
		return jiguanName;
	}

	public void setJiguanName(String jiguanName) {
		this.jiguanName = jiguanName;
	}
	
	public boolean[] getPopedom() {
		return popedom;
	}

	public void setPopedom(boolean[] popedom) {
		this.popedom = popedom;
	}

	public Long getCheckerId() {
		return checkerId;
	}

	public void setCheckerId(Long checkerId) {
		this.checkerId = checkerId;
	}

	public SysMsgInfoService getSysMsgInfoService() {
		return sysMsgInfoService;
	}

	public void setSysMsgInfoService(SysMsgInfoService sysMsgInfoService) {
		this.sysMsgInfoService = sysMsgInfoService;
	}
//***********************************************************
	@Override
	public PeopleInfo getModel() {
		return this.peopleInfo;
	}

	@Override
	public void prepare() throws Exception {
		
		if(self==1){
			this.setId(this.getCurrentUser().getPeople().getId());
		}
		if (id != null) {
			this.peopleInfo = peopleService.getPeopleInfoById(id);
		} else {
			this.peopleInfo = new PeopleInfo();
		}
		HashMap<String,Operation> oper=this.getOperMapByRoles(this.getCurrentUser().getRoles());
		PublicFunction.getOperationPopedom(oper,popedom,OperationConstants.PEOPLE_INFO);
	}
	protected void getDataList(DetachedCriteria query) {
		int totalRows = RequestUtils.getTotalRowsFromRequest(getRequest());
		if (totalRows < 0) {
			totalRows = peopleService.getPeopleInfoCountByCriteria(query);
		}
		int[] rowStartEnd = RequestUtils.getRowStartEnd(getRequest(),totalRows, DEFAULT_PAGE_SIZE, 0);
		Limit limit = RequestUtils.getLimit(getRequest(), "ec", totalRows,DEFAULT_PAGE_SIZE);
		int pageSize = limit.getCurrentRowsDisplayed();
		query.addOrder(Order.asc("joinDate"));
		query.setProjection(null);
		peopleInfoList.addAll(peopleService.getPeopleInfos(query, pageSize,rowStartEnd[0]));
	}
	@SuppressWarnings("deprecation")
	protected void showInfo() {
		Date currDate = new Date();
		int month = currDate.getMonth() - peopleInfo.getJoinDate().getMonth(); 
		if(month>=0){
			this.setGongling(currDate.getYear()-peopleInfo.getJoinDate().getYear());
		}
		else{
			this.setGongling(currDate.getYear()-peopleInfo.getJoinDate().getYear()-1);
		}
		if(peopleInfo.getDepart()!=null)
		{
			this.setDepartId(peopleInfo.getDepart().getId());
			this.setDepartName(peopleInfo.getDepart().getDepartName());
		}
		if(peopleInfo.getJiguan()!= null){
			this.setJiguanId(peopleInfo.getJiguan().getId());
			this.setJiguanName(peopleInfo.getJiguan().getPlace());
		}
		if(peopleInfo.getPosition()!=null)
		{
			this.setPositionId(peopleInfo.getPosition().getId());
			this.setPositionName(peopleInfo.getPosition().getPositionName());
		}
		if(peopleInfo.getXueli()!=null)
		{
			this.setXueliId(peopleInfo.getXueli().getId());
			this.setXueliName(peopleInfo.getXueli().getXueliName());
		}
		if (peopleInfo.getChecker()!=null) {
			this.checkerId = peopleInfo.getChecker().getId();
		}
	}
	//***********************************************************
	public String list() throws Exception{
			DetachedCriteria query = DetachedCriteria.forClass(PeopleInfo.class);
			//默认显示在职的
			Object[] state={1,2};
			query.add(Restrictions.in("state",state));
			getDataList(query);
			return SUCCESS;
	}	
	public String input() 

	{
		String peopleCode =this.peopleService.createPeopleCode();
		peopleInfo.setPeopleCode(peopleCode);
		return INPUT;
	}	
	
	public String edit() 
	{
		peopleInfo=this.peopleService.getPeopleInfoById(id);
		showInfo();
		return INPUT;
	}	
	
	/**
	 * @return
	 */
	public String selfInfo() {
		this.setId(this.getCurrentUser().getPeople().getId());
		peopleInfo = this.peopleService.getPeopleInfoById(id);
		showInfo();
		return SUCCESS;
	}
	
	/**
	 * ����
	 * @return
	 */
	public String save() throws Exception {			
		try {
			if (id == null) 
			{
				if( (upload!=null) && (upload.exists()) ){
					peopleInfo.setHeadPhoto(uploadHeadImg(upload));
				}else {
					peopleInfo.setHeadPhoto(headPhoto);
				}
				if (peopleInfo.getZzrq()!=null&&peopleInfo.getQuitDate()==null) {
					peopleInfo.setState(2);//在职
				} else if (peopleInfo.getQuitDate()!=null) {
					peopleInfo.setState(3);//离职
				}else if (peopleInfo.getJoinDate()!=null&&peopleInfo.getQuitDate()==null&&peopleInfo.getZzrq()==null) {
					peopleInfo.setState(1);//试用中
				}
					peopleService.savePeopleInfo(peopleInfo,departId,positionId,jiguanId,xueliId,checkerId);
				showInfo();
				this.addActionMessage(SystemMessage.SAVE_SUCCESS);
				return SUCCESS;
			} 
			else 
			{   
				if(upload.exists()){
					peopleInfo.setHeadPhoto(uploadHeadImg(upload));
				}else {
					peopleInfo.setHeadPhoto(headPhoto);
				}
				if (peopleInfo.getZzrq()!=null&&peopleInfo.getQuitDate()==null) {
					peopleInfo.setState(2);//在职
				} else if (peopleInfo.getQuitDate()!=null) {
					peopleInfo.setState(3);//离职
				}else if (peopleInfo.getJoinDate()!=null&&peopleInfo.getQuitDate()==null&&peopleInfo.getZzrq()==null) {
					peopleInfo.setState(1);//试用中
				}
					peopleService.updatePeopleInfo(peopleInfo,departId,positionId,jiguanId,xueliId,checkerId);
				showInfo();
				this.addActionMessage(SystemMessage.UPDATE_SUCCESS);
				return SUCCESS;					
			}
		} 
		catch (UniqueConstraintException e) 
		{	
			this.addActionError(e.getMessage());
			return INPUT;
		}
	}	

	public String uploadHeadImg(File upload )throws Exception{
		try {
			String urlString = "../../headPhoto/";
			String url = ServletActionContext.getServletContext().getRealPath("/headPhoto/");			
			File file_date = new File(url);
				if(!file_date.exists()){
					file_date.mkdirs();
				}
			String fileName = uploadFileName;
			String realName = UUID.randomUUID().toString() + getExt(fileName);
			File target = new File(url, realName);
			FileUtils.copyFile(upload, target);
			return (urlString+realName);
		} catch (Exception e) {
			e.printStackTrace();
			this.addActionError(e.getMessage());
			return null;
		}
	}
	
	/*
	 * 个人头像上传
	 */
	public String uploadHeadPhoto() throws Exception {
		try {
			String urlString = "../../headPhoto/";
			String url = ServletActionContext.getServletContext().getRealPath("/headPhoto/");
				File file_date = new File(url);
				if(!file_date.exists()){
					file_date.mkdirs();
				}
				if(upload.exists()){
					String fileName = uploadFileName;
					String realName = UUID.randomUUID().toString() + getExt(fileName);
					File target = new File(url, realName);
					FileUtils.copyFile(upload, target);
					
					addSysMsg(urlString+realName);
				}
			this.addActionMessage("附件已上传，正等待审核!");
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			this.addActionError("上传错误:" + e.getMessage());
			return SUCCESS;
		}
	}
	
	protected void addSysMsg(String imgUri){
		SysMsgInfo sysMsgInfo = new SysMsgInfo();
		sysMsgInfo.setMsgTitle("头像更新");
		sysMsgInfo.setMsgContent(this.getCurrentUser().getFullName()+"更新了头像，等待审核中！");
		sysMsgInfo.setReceiveUser(this.peopleService.getPeopleInfoById(id).getChecker().getId()+",");
		sysMsgInfo.setBusinessType(12);
		sysMsgInfo.setBusinessId(this.id);
		sysMsgInfo.setUrl(imgUri);
		sysMsgInfo.setCreateDate(new Date());
		sysMsgInfo.setCreater(this.getCurrentUser());
		sysMsgInfoService.saveSysMsgInfo(sysMsgInfo);
	}
	
	
	public static String getExt(String fileName) {
		if(fileName.lastIndexOf(".")>=0)
			return fileName.substring(fileName.lastIndexOf("."));
		else
			return "";
	}	
	
	
	/**
	 * @return
	 * @throws Exception
	 */
	public String search() throws Exception {
		DetachedCriteria query = DetachedCriteria.forClass(PeopleInfo.class);
		if (!StringTools.isNullOrSpace(this.getQCode())) {
			query.add(Restrictions.like("peopleCode", "%"+this.getQCode()+"%"));
		}
		if (null!=this.getQDepartId()) {
			query.createAlias("depart", "depart").add(Restrictions.eq("depart.id", this.getQDepartId()));
		}
		if (null!=this.getQPositionId()) {
			query.createAlias("position", "position").add(Restrictions.eq("position.id", this.getQPositionId()));
		}		
		if (null!=this.getQXueliId()) {
			query.createAlias("xueli", "xueli").add(Restrictions.eq("xueli.id", this.getQXueliId()));
		}		
		if (!StringTools.isNullOrSpace(this.getQPeopleName())) {
			query.add(Restrictions.like("peopleName", "%"+this.getQPeopleName()+"%"));
		}		
		if (!StringTools.isNullOrSpace(this.getQPoliticalStatus())) {
			query.add(Restrictions.like("politicalStatus", "%"+this.getQPoliticalStatus()+"%"));
		}		
		if (!StringTools.isNullOrSpace(this.getQIdNumber())) {
			query.add(Restrictions.like("idNumber", "%"+this.getQIdNumber()+"%"));
		}		
		if (this.qState>0) {
			query.add(Restrictions.like("state", this.qState));			
		}
			
		if(!StringTools.isNullOrSpace(this.getQRZStart())&& !StringTools.isNullOrSpace(this.getQRZEnd()))
		{				
			if(FORMAT.parse(this.getQRZStart()).before(FORMAT.parse(this.getQRZEnd())))
				query.add(Restrictions.between("joinDate",FORMAT.parse(this.getQRZStart()),DateTools.addDay(FORMAT.parse(this.getQRZEnd()), 1)));
			else  
				query.add(Restrictions.between("joinDate",FORMAT.parse(this.getQRZEnd()),DateTools.addDay(FORMAT.parse(this.getQRZStart()),1)));
		}		
		
		if(!StringTools.isNullOrSpace(this.getQZZStart())&& !StringTools.isNullOrSpace(this.getQZZEnd()))
		{				
			if(FORMAT.parse(this.getQZZStart()).before(FORMAT.parse(this.getQZZEnd())))
				query.add(Restrictions.between("zzrq",FORMAT.parse(this.getQZZStart()),DateTools.addDay(FORMAT.parse(this.getQZZEnd()), 1)));
			else  
				query.add(Restrictions.between("zzrq",FORMAT.parse(this.getQZZEnd()),DateTools.addDay(FORMAT.parse(this.getQZZStart()),1)));
		}
		getDataList(query);
		return SUCCESS;
	}	

	/**
	 * ɾ��
	 * 
	 * @return
	 */
	public String delete() throws Exception {
		if (id != null) 
		{	
			DetachedCriteria educationQuery = DetachedCriteria.forClass(PeopleEducation.class);
							 educationQuery.createAlias("people","people").add(
										Restrictions.eq("people.id",id));
			int totalRows1 = educationService.getEducationInfoCountByCriteria(educationQuery);
			
			DetachedCriteria experienceQuery = DetachedCriteria.forClass(PeopleExperience.class);
							 experienceQuery.createAlias("people","people").add(
									Restrictions.eq("people.id",id));
			int totalRows2 = experienceService.getExperienceInfoCountByCriteria(experienceQuery);
			
			DetachedCriteria trainQuery = DetachedCriteria.forClass(PeopleTrain.class);
							 trainQuery.createAlias("people","people").add(
									Restrictions.eq("people.id",id));
			int totalRows3 = trainService.getTrainInfoCountByCriteria(trainQuery);
			
			DetachedCriteria familyQuery = DetachedCriteria.forClass(PeopleFamily.class);
							 familyQuery.createAlias("people","people").add(
										Restrictions.eq("people.id",id));
			int totalRows4 = familyService.getFamilyInfoCountByCriteria(familyQuery);
			
			DetachedCriteria userQuery = DetachedCriteria.forClass(User.class);
			userQuery.createAlias("people","people").add(
						Restrictions.eq("people.id",id));
			int totalRows5 = userService.getUsersCount(userQuery);	
			
			if(totalRows1>0 || totalRows2>0 || totalRows3>0 || totalRows4>0 || totalRows5>0){
				this.addActionMessage("已经发生过业务逻辑，不能删除！");
				return INPUT;
			}else{
				peopleService.removePeopleInfo(id);
				return SUCCESS;				
			}

		}
		this.addActionMessage("编号为空，请选择具体的记录！");
		return INPUT;
	}

	public String warn() throws Exception {
		peopleInfoList.clear();				
			SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd");
			
			String currDate = FORMAT.format(new Date());//��ǰϵͳ������
			Long currTime = FORMAT.parse(currDate).getTime();
			int i;
			for(i=0;i<peopleService.getPeopleInfos( ).size();i++){
				Date  birthday = FORMAT.parse(peopleService.getPeopleInfos().get(i).getBirthday().toString());
				Long birthTime = birthday.getTime();
				if((birthTime - currTime)/(1000*60*60*24)<=3 && (birthTime - currTime)/(1000*60*60*24)>0){
					peopleInfoList.add(peopleService.getPeopleInfos().get(i));
				}				
			}
			
			return SUCCESS;
		
	}

	public String select()
	{
		DetachedCriteria query=DetachedCriteria.forClass(PeopleInfo.class);
		
		//query.add(Restrictions.eq("deleteFlag",false));
		query.add(Restrictions.isNull("quitDate"));
		peopleInfoList.addAll(peopleService.getPeopleInfos(query));			
		return SUCCESS;
	}



	
	

	
}
